﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace Battle
{
    public class ScoredTable : TableLayoutPanel
    {
        private readonly Fighter _fighter1;
        private readonly Fighter _fighter2;
        private readonly int _shipsPerFight;
        private readonly Label _scoredLabel;

        private static readonly Color ColorForActiveFighter = Color.FromArgb(128, 128, 128);
        private static readonly Color ColorForNonActiveFighter = Color.FromArgb(33, 98, 17);    
        private static readonly Color ColorForFighter = Color.FromArgb(128, 128, 128);
        private static readonly Color ColorForWinner = Color.FromArgb(32, 167, 8);
        private static readonly Color ColorForLooser = Color.FromArgb(222, 0, 0);
        private static readonly Color ScoredColor = Color.Red;

        private readonly Battle<Label, Label> _fighterNames;
        private readonly Battle<Label, Label> _fighterStats;

        private Point _score;
        private Point _shipsRemained;

        public event EventHandler FightEnded;

        public ScoredTable(Fighter fighter1, Fighter fighter2, int shipsPerFight)
        {
            _fighter1 = fighter1;
            _fighter2 = fighter2;

            _shipsPerFight = shipsPerFight;

            _fighter1.Fight += OnFighterTurnChanged;
            _fighter2.Fight += OnFighterTurnChanged;

            _fighter1.Figh += OnFighterMadeShot;
            _fighter2.Figh += OnFighterMadeShot;

            _fighterNames = new Battle<Label, Label>((Labell(_fighter1.Name, ColorForNonActiveFighter)), (Labell(_fighter2.Name, ColorForNonActiveFighter)));
            _fighterStats = new Battle<Label, Label>((Labell(string.Empty, Color.Red)), (Labell(string.Empty, Color.Red)));
            
            _scoredLabel = Labell("", ScoredColor);

            UpdateScore();
            InitFighterStats();
        }

// Ініціальзація змінних для відображення результатів
        private void InitFighterStats()
        {
            _shipsRemained = new Point(_shipsPerFight, _shipsPerFight);
            RefreshFighterStats();
        }

// Формування характеристик лейб
        private static Label Labell(string text, Color color)
        {
            return new Label
                       {
                           Padding = Padding.Empty,
                           ForeColor = color,
                           TextAlign = ContentAlignment.TopLeft,
                           AutoSize = true,
                           Text = text,
                           Dock = DockStyle.Fill,
                           Margin = Padding.Empty,
                           Font = new System.Drawing.Font("Arial Unicode MS", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))),
                       };
        }

// при пострілі оновлення лічильників пострілів та кораблів потопленних, оновлення кольорів гравців
        private void OnFighterMadeShot(object sender, ShootingEventArgs e)
        {
            if (sender == _fighter1)
            {
                if (e.Result == ShotingEnum.Drowned)
                {
                    _shipsRemained.Y--;
                }
            }
            else
            {
                if (e.Result == ShotingEnum.Drowned)
                {
                    _shipsRemained.X--;
                }
            }
            TrackResult();
            RefreshFighterStats();
        }

// Оновлення лічильників на полі
        private void RefreshFighterStats()
        {
            _fighterStats.Computer.Text = string.Format("{0} Countdown", _shipsRemained.X);
            _fighterStats.Human.Text = string.Format("{0} Countdown", _shipsRemained.Y);
        }

// Зміна кольорів бійців при при передачі права пострілів іншому бійцю
        private void OnFighterTurnChanged(object sender, EventArgs e)
        {
            var color1 = sender == _fighter1 ? ColorForActiveFighter : ColorForNonActiveFighter;
            var color2 = sender == _fighter2 ? ColorForActiveFighter : ColorForNonActiveFighter;
            
            _fighterNames.Computer.ForeColor = color1;
            _fighterNames.Human.ForeColor = color2;
        }

// Перевірка чи закінчився бій
        public bool FightHasEnded()
        {
            return _shipsRemained.X == 0 || _shipsRemained.Y == 0;
        } 

// Кольори
        private void TrackResult()
        {
            if (!FightHasEnded())
            {
                return;
            }
            Color color1;
            Color color2;
            if (_shipsRemained.X == 0)
            {
                _score.Y++;
                color1 = ColorForLooser;
                color2 = ColorForWinner;
            }
            else
            {
                _score.X++;
                color1 = ColorForWinner;
                color2 = ColorForLooser;
            }
            _fighterNames.Computer.ForeColor = color1;
            _fighterNames.Human.ForeColor = color2;
            UpdateScore();
            var handler = FightEnded;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

//Оновлення результатів виграних боїв 
        private void UpdateScore()
        {
            _scoredLabel.Text = string.Format("{0} : {1}", _score.X, _score.Y);
            if (_score.X > 0 || _score.Y > 0)
            {
                if (_shipsRemained.X == 0)
                {
                    LooserForm l = new LooserForm();
                    l.Show(); 
                }
                else
                {                    
                    WinerForm q = new WinerForm();
                    q.Show();
                }
            }
        }

//  Підготовка поля для новоого бою
        public void NewFightOnTable()
        {
            InitFighterStats();
            RefreshFighterStats();
            _fighterNames.Computer.ForeColor = ColorForNonActiveFighter;
            _fighterNames.Human.ForeColor = ColorForNonActiveFighter;
        }


        // Перевизначення для розміщення лейб (лічильники, результати)
        private void AddLayoutColumns()
        {
            ColumnCount = 3;
            ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40));
            ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
            ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40));
            //BackgroundImage = Image.FromFile(Application.StartupPath + "\\" + @"images.jpg");
            BackgroundImage = Resource1.images;
        }

        private void AddLayoutRows()
        {
            RowCount = 2;
            RowStyles.Add(new RowStyle(SizeType.AutoSize, 50));
            RowStyles.Add(new RowStyle(SizeType.AutoSize, 50));
            //BackgroundImage = Image.FromFile(Application.StartupPath + "\\" + @"images.jpg");
            BackgroundImage = Resource1.images;
        }

        protected override void InitLayout()
        {
            base.InitLayout();
            
            Padding = Margin = Padding.Empty;
            Font =  new System.Drawing.Font("Arial Unicode MS", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            AddLayoutColumns();
            AddLayoutRows();
            _fighterNames.Computer.Font = new Font(Font.FontFamily, 30);
            _fighterNames.Computer.BackgroundImage = Resource1.images;

            Controls.Add(_fighterNames.Computer, 0, 0);
            _fighterNames.Human.Font = new Font(Font.FontFamily, 30);
            _fighterNames.Human.TextAlign = ContentAlignment.TopRight;
            _fighterNames.Human.BackgroundImage = Resource1.images;
            Controls.Add(_fighterNames.Human, 2, 0);
            _scoredLabel.Font = new Font(Font.FontFamily, 40, FontStyle.Bold);
            _scoredLabel.TextAlign = ContentAlignment.TopCenter;
            _scoredLabel.BackgroundImage = Resource1.images;
            Controls.Add(_scoredLabel, 1, 0);
            _fighterStats.Computer.Font = Font;
            _fighterStats.Computer.BackgroundImage = Resource1.images;
            Controls.Add(_fighterStats.Computer, 0, 1);
            _fighterStats.Human.Font = Font;
            _fighterStats.Human.TextAlign = ContentAlignment.TopRight;
            _fighterStats.Human.BackgroundImage = Resource1.images;
            Controls.Add(_fighterStats.Human, 2, 1);    
            Height = _fighterNames.Computer.Height + _fighterStats.Computer.Height;
           
        }
    }
}